package com.gouqi.mall.controller;

import com.gouqi.mall.utils.FileUtil;
import com.gouqi.mall.utils.URLUtils;
import io.swagger.annotations.*;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author xiaofei
 * @time:2020-01-12
 */
@CrossOrigin
@Api(basePath = "/api/v1", value = "文件上传接口", description = "文件上传")
@Component
@RestController
@RequestMapping(value = "/upload")
public class FileUploadController extends BaseController{

    /**
     * 上传单张图片
     * @param multipartFile
     * @return
     * @throws FileNotFoundException
     */
    @ResponseBody
    @RequestMapping(value = "/image",method = RequestMethod.POST,consumes = "multipart/*",headers = "content-type=multipart/form-data",produces = "application/json")
    @ApiOperation(value = "文件上传",notes = "上传一个图片文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "multipartFile", paramType="form", value = "临时文件", dataType="file", required = true)
    })
    public String uploadImage(@RequestParam(name = "multipartFile") MultipartFile multipartFile, HttpServletRequest request) throws FileNotFoundException {
        System.out.println("文件：" + multipartFile);
        JSONObject jsonObject = new JSONObject();
        //随机生成文件File Key
        String filekey = UUID.randomUUID().toString();
        String fileName = multipartFile.getOriginalFilename();
        System.out.println("文件名："+fileName);
        //获取文件后缀
        String suffix = fileName.substring(fileName.indexOf("."));
        String basePath = "E:/static/upload/";
        //按日期命名文件
        Date todayDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String today = dateFormat.format(todayDate);
        // 域名访问的相对路径（通过浏览器访问的链接-虚拟路径）
        basePath = basePath + today + "/";
        // 真实路径，实际储存的路径
        // String realPath = accessPath + today + "/";
        String filePath =  basePath;
        String newFileName = filekey + suffix;
        if (".png".equals(suffix) || ".jpg".equals(suffix)){
            //获取协议ip和端口号
            String origin = URLUtils.getOrigin(request);
            //图片地址
            String imageUrl = origin +"/upload/"+today+"/"+newFileName;
            File file = new File(filePath + newFileName);
            //上传文件
            jsonObject.put("result","success");
            jsonObject.put("msg","是图片");
            jsonObject.put("status","200");
            jsonObject.put("url",imageUrl);
            jsonObject.put("uid",UUID.randomUUID().toString());
            jsonObject.put("name",filekey);
            jsonObject.put("fileName",newFileName);
            jsonObject.put("path","/upload/"+today);
            try {
                FileUtil.uploadFile(multipartFile.getBytes(),filePath,newFileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            jsonObject.put("msg","不是图片，请选择图片");
            jsonObject.put("result","failed");
            jsonObject.put("status","404");
        }
        return jsonObject.toString();
    }
}
